<?php
/**
 * Created by IntelliJ IDEA.
 * User: ftavora
 * Date: 03/02/2015
 * Time: 11:25
 */

namespace CAI\HistoricoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use CAI\HistoricoBundle\Entity\TorneoInstancia;
use CAI\HistoricoBundle\Entity\Torneo;
use CAI\HistoricoBundle\Form\Type\TorneoInstanciaType;
use CAI\HistoricoBundle\Form\Type\TorneoType;

use \Doctrine\DBAL\DBALException;

class AjaxTorneosController extends AjaxBaseController
{
    public function ajaxGuardarTorneoInstanciaAction(Request $request)
    {
        if($request->isXmlHttpRequest()) {
            $torneo_instancia = new TorneoInstancia();
            $form = $this->createForm(new TorneoInstanciaType(), $torneo_instancia);
            $form->handleRequest($request);

            $t = $form->getData();

            $id = $this->getDoctrine()->getRepository('CAIHistoricoBundle:TorneoInstancia');
            $query = $id->createQueryBuilder('ti')
                ->select('ti, MAX(ti.torneos_instancias_id) AS max_id');
            $maxId = $query->getQuery()->getResult();

            $t->setTorneosInstanciasId($maxId[0]['max_id'] +1);

            $em = $this->getDoctrine()->getManager();
            $em->persist($t);
            $em->flush();

            return new Response();
        }else{
            return new Response("Invalid request");
        }
    }

    public function ajaxGuardarTorneoAction(Request $request)
    {
        if($request->isXmlHttpRequest()) {
            $torneo = new Torneo();
            $form = $this->createForm(new TorneoType(), $torneo);
            $form->handleRequest($request);

            $t = $form->getData();

            $id = $this->getDoctrine()->getRepository('CAIHistoricoBundle:Torneo');
            $query = $id->createQueryBuilder('t')
                ->select('t, MAX(t.torneos_id) AS max_id');
            $maxId = $query->getQuery()->getResult();

            $t->setTorneosId($maxId[0]['max_id'] +1);

            $em = $this->getDoctrine()->getManager();
            $em->persist($t);
            $em->flush();

            return new Response();
        }else{
            return new Response("Invalid request");
        }
    }

}